import React, { useState } from 'react';
import { Checkbox, Form, Icon, Input, Message, Select } from '@alifd/next';
import styles from './index.module.scss';
import { useHistory } from 'ice';

const { Item } = Form;

export interface IDataSource {
  name: string;
  password: string;
  autoLogin: boolean;
  store: number;
}

const DEFAULT_DATA: IDataSource = {
  name: '',
  password: '',
  autoLogin: true,
};

interface LoginProps {
  dataSource?: IDataSource;
}

const LoginBlock: React.FunctionComponent<LoginProps> = (props = { dataSource: DEFAULT_DATA }): JSX.Element => {
  const { dataSource = DEFAULT_DATA } = props;

  const history = useHistory();

  const [postData, setValue] = useState(dataSource);

  const formChange = (values: IDataSource) => {
    setValue(values);
  };

  const handleSubmit = (values: IDataSource, errors: []) => {
    if (errors) {
      console.log('errors', errors);
      return;
    }
    if (values.name === 'admin' && values.password === 'admin') {
      sessionStorage.setItem('token', 'admin');
    }

    if (values.store) {
      sessionStorage.setItem('store', String(values.store));
    }
    Message.success('登录成功');
    history.push('/');
  };

  return (
    <div className={styles.LoginBlock}>
      <div className={styles.innerBlock}>
        <h2 className={styles.logo}>健康档案管理</h2>
        <div className={styles.desc}>
          <span className={styles.active}>账户密码登录</span>
        </div>

        <Form value={postData} onChange={formChange} size="large">
          <Item required requiredMessage="门店必选">
            <Select name="store" placeholder="请选择门店" style={{ width: '100%' }}>
              <Select.Option value={0}>总系统</Select.Option>
              <Select.Option value={1}>门店1</Select.Option>
              <Select.Option value={2}>门店2</Select.Option>
            </Select>
          </Item>
          <Item required requiredMessage="用户名必填">
            <Input name="name" maxLength={20} placeholder="用户名" />
          </Item>
          <Item required requiredMessage="密码必填" style={{ marginBottom: 0 }}>
            <Input.Password name="password" htmlType="password" placeholder="密码" />
          </Item>

          <div className={styles.infoLine}>
            <Item style={{ marginBottom: 0 }}>
              <Checkbox name="autoLogin" className={styles.infoLeft}>
                自动登录
              </Checkbox>
            </Item>
          </div>

          <Item style={{ marginBottom: 10 }}>
            <Form.Submit type="primary" onClick={handleSubmit} className={styles.submitBtn} validate>
              登录
            </Form.Submit>
          </Item>
          <div className={styles.infoLine}>
            <div className={styles.infoLeft}>
              其他登录方式 <Icon type="atm" size="small" /> <Icon type="atm" size="small" />{' '}
              <Icon type="atm" size="small" />
            </div>
          </div>
        </Form>
      </div>
    </div>
  );
};

export default LoginBlock;
